﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class PropertyComponent : NetworkBehaviour
{
    public Slider slider_hp;
    [SyncVar(hook = "OnChangeHealth")] public int hp;
    private float maxHp = 100;
    private PlayerData playerData;

    void Start()
    {
        playerData = new PlayerData(100);
        hp = playerData.hp;
        OnChangeHealth(hp);
    }

    [Command]
    public void CmdTakeDamage(uint id, int num)
    {
        RpcTakeDamage(id, num);
    }

    [ClientRpc]
    void RpcTakeDamage(uint id, int num)
    {
        Game.GetComp<ActorManager>().TakeDamage(id,num);
    }

    void OnChangeHealth(int health)
    {
        playerData.hp = health;
        slider_hp.value = (float)health / playerData.maxHp;
        if (isLocalPlayer)
        {
            Slider sliderHp = Game.UI.GetUI<UI_Battle>().selfView.slider_hp;
            bool isHurt = (float)health / playerData.maxHp < sliderHp.value;
            sliderHp.value = (float)health / playerData.maxHp;
            if (isHurt)
            {
                Game.UI.GetUI<UI_Hurt>().Hurt();
            }
        }
    }

    [Server]
    public void OnHurt(int num)
    {
        hp += num;
    }
}
